package com.gexiaobao.pigeon.ui.auction

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.RxTextTool
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.param.ReSendSMSParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityMarginPaymentBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterRechargeMoney
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.viewmodel.AuctionViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.ext.view.textString
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.text.DecimalFormat


/**
 * @Author      : hxw
 * @Date        : 2024/11/13 11:03
 * @Describe    : 保证金缴纳
 */
class ActivityMarginPayment : BaseActivity<AuctionViewModel, ActivityMarginPaymentBinding>() {

    private var mRemainMoney: Double = 0.0
    private var orderId: Int = 0
    private val adapter: AdapterRechargeMoney by lazy { AdapterRechargeMoney(arrayListOf()) }
    private var payPassDialog: PayPassDialog? = null
    private var payDialog: RxPayDialog? = null

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.tvReturnMargin.paint.flags = Paint.UNDERLINE_TEXT_FLAG//设置下划线
        mDatabind.tvAllReturnMargin.isVisible = false
        mDatabind.recyclerView.init(GridLayoutManager(this, 3), adapter)
            .addItemDecoration(SpaceItemDecoration(Util.dp2px(this, 10f), Util.dp2px(this, 30f)))

        initAdapterData()
        mViewModel.getTotalFreezeMoney()
        setMarginBalance()

        eventViewModel.toRefreshData.observeInActivity(this) {
            mViewModel.getTotalFreezeMoney()
        }
        mDatabind.swipeRefreshLayout.init {
            mViewModel.getTotalFreezeMoney()
        }

//        mDatabind.etMarginPaymentMoney.addTextChangedListener(object : TextWatcher {
//            var isFormatting = false  // 防止无限循环格式化
//            override fun beforeTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {}
//            override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {}
//            override fun afterTextChanged(editable: Editable?) {
//                if (isFormatting) return  // 防止重复格式化
//                isFormatting = true
//                // 获取当前输入的原始文本，并移除掉非数字字符
//                val originalString = editable.toString().replace("\\D".toRegex(), "")
//                // 如果输入为空，则清空
//                if (originalString.isEmpty()) {
//                    mDatabind.etMarginPaymentMoney.setText("")
//                    mDatabind.etMarginPaymentMoney.setSelection(0)
//                    isFormatting = false
//                    return
//                }
//                // 格式化数字为逗号分隔的字符串
//                val formatted = formatWithComma(originalString)
//                // 设置格式化后的文本
//                mDatabind.etMarginPaymentMoney.setText(formatted)
//                // 保持光标在文本的末尾
//                mDatabind.etMarginPaymentMoney.setSelection(formatted.length)
//                isFormatting = false
//            }
//        })
    }

    // 格式化数字为带逗号的字符串
    fun formatWithComma(number: String): String {
        val numberFormat = DecimalFormat("#,###")
        val parsedNumber = number.toLongOrNull()
        return if (parsedNumber != null) {
            numberFormat.format(parsedNumber)
        } else {
            number
        }
    }

    private fun formatAmount(amount: Double): String {
        val formatter = DecimalFormat("#,###.00")
        return formatter.format(amount)
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initAdapterData() {
        val mList = listOf("￥200", "￥500", "￥800", "￥1200", "￥1500", "￥1800")
        adapter.setList(mList)
        adapter.notifyDataSetChanged()

        adapter.setOnItemClickListener { _, _, position ->
            mDatabind.etMarginPaymentMoney.setText(mList[position].substring(1, mList[position].length))
            mDatabind.etMarginPaymentMoney.setSelection(mDatabind.etMarginPaymentMoney.text.toString().length)
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取保证金信息 */
        mViewModel.freezeMoneyResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            mRemainMoney = it.remainMoney
            setMarginBalance()
        }
        /** 重新发送验证码  */
        mViewModel.reSendSMSResult.observe(this) {
            dismissLoading()
            if (!it.isSuccess) {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 申请缴纳保证金 */
        mViewModel.applyPayDepositResult.observe(this) {
            orderId = it.orderId
            showPayDialog()
        }
        /** 确认缴纳保证金 */
        mViewModel.confirmPayDepositResult.observe(this) {
            if (it.isSuccess) {
                eventViewModel.toRefreshData.value = true
                paySuccess()
            } else {
                RxToast.error(it.errorMsg)
            }
            payPassDialog?.dismiss()
        }
    }

    private fun setMarginBalance() {
        val mRemainMoney = if (mRemainMoney >= 1000) {
            formatAmount(mRemainMoney)
        } else {
            mRemainMoney
        }
        RxTextTool.getBuilder("当前保证金余额: ")
            .append("￥$mRemainMoney").setAppearance(56).setBold()
            .setTextColor(ContextCompat.getColor(this, R.color.color_fe4542))
            .into(mDatabind.tvMarginBalance)
    }

    private fun reSendSMS() {
        val body = ReSendSMSParam(orderId = orderId)
        mViewModel.reSendSMS(body)
    }

    private fun showPayDialog() {
        payPassDialog = PayPassDialog(this)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            @SuppressLint("SetTextI18n")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast("关闭支付")
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                reSendSMS()
            }

            override fun onPassFinish(verifyCode: String?) {
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val map = mapOf("orderId" to orderId, "verificationCode" to verifyCode)
                    val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                    mViewModel.confirmPayDeposit(body)
                }, lifecycleScope)
            }
        })
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvMarginPaymentTopUp, mDatabind.ivMarginPaymentBack, mDatabind.tvReturnMargin) {
            when (it) {
                mDatabind.tvReturnMargin -> startActivity<ActivityReturnMargin>()
                mDatabind.ivMarginPaymentBack -> finish()
                mDatabind.tvMarginPaymentTopUp -> auctionTopUp()
            }
        }
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(this)
        payDialog!!.loadingDialog()
        payDialog!!.setCancelListener {
            payDialog!!.dismiss()
            finish()
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }

    private fun paySuccess() {
        payDialog!!.showBottomBtnSingle()
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent(getString(R.string.payment_success))
    }

    private fun auctionTopUp() {
        val price = mDatabind.etMarginPaymentMoney.textString()
        if (price.isEmpty()) {
            RxToast.warning("请输入充值金额")
            return
        }
        val map = mapOf("money" to price.toInt())
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        showLoading(getString(R.string.loading))
        mViewModel.applyPayDeposit(body)
    }
}